package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Transactional
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper logsMapper;

    @Autowired
    private CacheService cacheService;

    /**
     * 添加任务
     *
     * @param task
     */
    @Override
    public Long addTask(Task task) {
        //1. 把任务数据添加到数据库
        boolean success = addTaskToDb(task);
        //2. 把任务添加到redis-不是所有的任务都需要添加到redis(立即执行、未来5分钟要执行的任务)
        if(success){
            addTaskToRedis(task);
        }

        return task.getTaskId();
    }

    /**
     * 取消任务
     *
     * @param taskId 任务id
     * @return 取消结果
     */
    @Override
    public boolean cancelTask(long taskId) {
        boolean flag = true;
        //操作数据库删除任务数据冰更新日志表的状态
        Task task = updateDb(taskId,ScheduleConstants.CANCELLED);
        // 删除redis中的数据
        if(null != task){
            removeTaskFromCache(task);
        }

        return flag;
    }

    /**
     * 按照类型和优先级来拉取任务
     *
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task poll(int type, int priority) {
        String key = type + "_"+priority;
        String json = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
        if(StringUtils.isNotEmpty(json)){
            Task task = JSON.parseObject(json, Task.class);

            //只要拉取成功一个任务默认在这个任务就代表消费成功了
            updateDb(task.getTaskId(), ScheduleConstants.EXECUTED);

            return task;
        }

        return null;
    }

    /**
     * 删除redis中的任务数据
     * @param task
     */
    private void removeTaskFromCache(Task task) {
        String key = task.getTaskType() + "_" + task.getPriority();

        if(task.getExecuteTime() <= System.currentTimeMillis()){
            cacheService.lRemove(ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(task));
        }else{
            cacheService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(task));
        }
    }

    private Task updateDb(long taskId, int status) {
        //1. 根据id删除任务数据
        taskinfoMapper.deleteById(taskId);

        //2. 更新日志表的状态数据
        TaskinfoLogs logs = logsMapper.selectById(taskId);
        logs.setStatus(status);
        logsMapper.updateById(logs);

        Task task = new Task();
        BeanUtils.copyProperties(logs, task);
        task.setExecuteTime(logs.getExecuteTime().getTime());

        return task;
    }

    /**
     * 添加数据到redis
     * @param task
     */
    private void addTaskToRedis(Task task) {
        String key = task.getTaskType() + "_" + task.getPriority();

        //可以使用日历类来完成时间的操作
        Calendar calendar = Calendar.getInstance(); // 用当前时间初始化一个日历
        calendar.add(Calendar.MINUTE, 5); // 把日志的时间设置到了未来的5分钟
        long future = calendar.getTimeInMillis();

        //任务执行的时间小于等于当前时间- 添加到list集合立即执行的任务
        if(task.getExecuteTime() <= System.currentTimeMillis()){
            cacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
        }else if(task.getExecuteTime() <= future){
            //任务执行的时间小于等于当前时间+5分钟
            cacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task), task.getExecuteTime());
        }
    }

    /**
     * 添加任务到数据库
     * @param task
     * @return
     */
    private boolean addTaskToDb(Task task) {
        //1. 添加TaskInfo表的数据
        Taskinfo taskinfo = new Taskinfo();
        BeanUtils.copyProperties(task, taskinfo);
        taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
        int status = taskinfoMapper.insert(taskinfo);

        //2. 添加TaskInfoLogs表的数据
        TaskinfoLogs logs = new TaskinfoLogs();
        BeanUtils.copyProperties(task, logs);
        logs.setExecuteTime(new Date(task.getExecuteTime()));
        logs.setVersion(1);
        logs.setStatus(ScheduleConstants.SCHEDULED);
        logs.setTaskId(taskinfo.getTaskId());

        int result = logsMapper.insert(logs);

        task.setTaskId(taskinfo.getTaskId());

        return status == 1 && result == 1;
    }


    /**
     * 每分钟定时刷新zset中的数据到list
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh() {
        //0. 获取分布式锁如果成功则执行定时任务
        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);

        if(null != token){
            //1. 获取zset中的锁有的key的数据
            /**
             * futureKeys:
             *   future_1_50 -list -> 包含N多的数据(任务)
             *   future_1_51
             *   future_2_50
             *   future_2_51
             */
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");

            //2. 遍历所有的key
            for (String futureKey : futureKeys) { // future_1_50
                //3. 得到按当前遍历key里面所有过期的任务
                Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());

                String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];// topic_1_50

                //4. 通过管道技术添加到list集合
                if(!tasks.isEmpty()){
                    cacheService.refreshWithPipeline(futureKey, topicKey, tasks);
                }
            }
        }
    }

    /**
     * PostConstruct: 作用对象的初始化方法-当对象创建完成以后就会调用该方法完成数据的初始化操作
     */
    @Scheduled(cron = "0 */5 * * * ?")
    @PostConstruct
    public void reloadData(){
        //1. 清除redis中的数据-list zset
        clearRedis();

        //2. 查询未来5分钟之内要执行的任务
        Calendar calendar = Calendar.getInstance(); // 用当前时间初始化一个日历
        calendar.add(Calendar.MINUTE, 5); // 把日志的时间设置到了未来的5分钟
        List<Taskinfo> taskinfoList = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, calendar.getTime()));

        //3. 重新吧任务添加到redis的缓存
        if(null != taskinfoList && taskinfoList.size()>0){
            for (Taskinfo taskinfo : taskinfoList) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo, task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());

                //添加到redis
                addTaskToRedis(task);
            }
        }
    }

    /**
     * 清除redis中的数据
     */
    private void clearRedis() {
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");

        cacheService.delete(futureKeys);
        cacheService.delete(topicKeys);
    }
}
